package com.itheima.project.intercept;

import com.alibaba.fastjson.JSONObject;
import com.itheima.project.constant.SuperConstant;
import com.itheima.project.constant.security.OauthCacheConstant;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.SubjectContent;
import com.itheima.project.vo.security.UserVo;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName TenantIntercept.java
 * @Description 多租户放到SubjectContent上下文中
 */
@Component
public class TenantIntercept implements HandlerInterceptor {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String userToken = request.getHeader(SuperConstant.USER_TOKEN);
        if (!EmptyUtil.isNullOrEmpty(userToken)){
            RBucket<UserVo> jtiUserBucket = redissonClient.getBucket(OauthCacheConstant.JTI_USER + userToken);
            UserVo userVo = jtiUserBucket.get();
            //放入当前线程中：用户当前的web直接获得user使用
            SubjectContent.setSubject(JSONObject.toJSONString(userVo));
            //从头部中拿到用户对应的企业信息
            Long enterpriseId = userVo.getEnterpriseId();
            //放入当前线程中：用户当前的web直接获得user使用
            SubjectContent.setEnterprise(String.valueOf(enterpriseId));
            //保留想现有fegin接口传递userToken
            SubjectContent.setUserToKen(userToken);
        }

        //从头部中拿到当前storeId
        String storeId = request.getHeader(SuperConstant.STORE_TOKEN);
        if (!EmptyUtil.isNullOrEmpty(storeId)){
            //放入当前线程中：用户当前的web直接获得storeId使用
            SubjectContent.setStore(storeId);
        }

        //从头部中拿到当前是否开启多租户
        String enableTenant = request.getHeader(SuperConstant.ENABLE_TENANT);
        if (!EmptyUtil.isNullOrEmpty(enableTenant)){
            //放入当前线程中：用户当前的web直接获得storeId使用
            SubjectContent.setTenantEnable(Boolean.valueOf(enableTenant));
        }

        // 多租户隔离判断
       /* String host = null;
        Enumeration<String> headers = request.getHeaders("x-forwarded-host");

        if (!EmptyUtil.isNullOrEmpty(headers.nextElement())) {
            host = headers.nextElement().split(",")[0].split(":")[0];
        }
        String key = EnterpriseCacheConstant.WEBSITE+host;
        RBucket<EnterpriseVo> bucket = redissonClient.getBucket(key);
        EnterpriseVo enterpriseVo = bucket.get();
        if (EmptyUtil.isNullOrEmpty(enterpriseVo)){
            throw  new ProjectException(AuthEnum.HSOT_FAIL);
        }
        if (SuperConstant.YES.equals(enterpriseVo.getIsEnterprise())) {
            //放入当前线程中：用户当前的web直接获得storeId使用
            SubjectContent.setTenantEnable(true);
        }else {
            SubjectContent.setTenantEnable(false);
        }*/
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除当前线程中的参数
        SubjectContent.removeSubject();
        SubjectContent.removeTenantEnable();
        SubjectContent.removeEnterprise();
        SubjectContent.removeStore();
        SubjectContent.removeUserToKen();
    }
}
